﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ReactiveXLearning
{
    public partial class frmTimeout : frmBase
    {

        public frmTimeout()
        {
            InitializeComponent();
            Load += FrmTimeout_Load;
            FormClosed += FrmTimeout_FormClosed;
        }

        private void FrmTimeout_Load(object sender, EventArgs e)
        {
            //事件
            btn_copy.Click += Btn_copy_Click;

            var clicks = Observable.FromEventPattern
                <MouseEventHandler, MouseEventArgs>(
                    handler => (s, a) => handler(s, a),
                    handler => MouseDown += handler,
                    handler => MouseDown -= handler)
                    .Select(x => x.EventArgs.Location);

            Observable.FromEventPattern
                <MouseEventHandler, MouseEventArgs>(
                    handler => (s, a) => handler(s, a),
                    handler => MouseMove += handler,
                    handler => MouseMove -= handler)
                    .Select(x => x.EventArgs.Location)
                    .Timeout(TimeSpan.FromSeconds(1), clicks) //事件相隔 1 秒未发送后，事件流被替换成clicks
                    .Subscribe(
                    x => WriteLine("当前秒：" + DateTime.Now.Second + ": 当前位置 " + x.X + "," + x.Y),
                    ex => WriteLine(ex));
        }

        private void FrmTimeout_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void Btn_copy_Click(object sender, EventArgs e)
        {
            var copys = new StringBuilder();
            var select_items = new List<object>();
            foreach (var item in lb_out.SelectedItems) select_items.Add(item);
            select_items.ToObservable()
                .Select(x => Convert.ToString(x))
                .Where(x => !string.IsNullOrWhiteSpace(x))
                .Subscribe(item => copys.AppendLine(item), () => Clipboard.SetDataObject(copys.ToString()));
        }

        private void WriteLine(object obj)
        {
            RunOnUI(() =>
            {
                lb_out.Items.Add(obj);
                lb_out.SelectedIndex = lb_out.Items.Count - 1;
            });
        }
    }
}
